package com.codecrane.core.util;

import java.util.Properties;

/**
 * 数据库备份还原工具类
 * Created by crane on 2017/6/12.
 */
public class BackupUtil {
    /**
     * 导出SQL
     *
     * @param properties
     */
    public static void ExptSQL(Properties properties) {
        RuntimeUtil.execte(getExptCmd(properties));
    }

    /**
     * 导入SQL
     *
     * @param properties
     */
    public static void ImptSQL(Properties properties) {
        RuntimeUtil.execte(getImptCmd(properties));
    }

    /**
     * 获取导出命令
     *
     * @param properties
     * @return
     */
    public static String getExptCmd(Properties properties) {
        StringBuffer cmd = new StringBuffer();
        cmd.append(getOSCmd()).append(" ");
        cmd.append("mysqldump").append(" ");
        cmd.append("-h").append(properties.getProperty("ip")).append(" ");
        cmd.append("-u").append(properties.getProperty("user")).append(" ");
        cmd.append("-p").append(properties.getProperty("password")).append(" ");
        cmd.append("-P").append(properties.getProperty("port")).append(" ");
        cmd.append(properties.getProperty("database")).append(" ").append(">").append(" ");
        cmd.append(properties.getProperty("path")).append(properties.getProperty("filename"));
        return cmd.toString();
    }

    /**
     * 获取导入命令
     *
     * @param properties
     * @return
     */
    public static String getImptCmd(Properties properties) {
        StringBuffer cmd = new StringBuffer();
        cmd.append(getOSCmd()).append(" ");
        cmd.append("mysql").append(" ");
        cmd.append("-h").append(properties.getProperty("ip")).append(" ");
        cmd.append("-u").append(properties.getProperty("user")).append(" ");
        cmd.append("-p").append(properties.getProperty("password")).append(" ");
        cmd.append("-P").append(properties.getProperty("port")).append(" ");
        cmd.append(properties.getProperty("database")).append(" ").append("<").append(" ");
        cmd.append(properties.getProperty("path")).append(properties.getProperty("filename"));
        return cmd.toString();
    }

    /**
     * 获取当前系统命令
     *
     * @return
     */
    public static String getOSCmd() {
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            return "cmd /c";
        } else if (osName.contains("Linux")) {
            return "sh -c";
        }
        return "";
    }

}
